//
//  RegisterViewController.m
//  FloatClouds
//
//  Created by 黄威 on 16/8/29.
//  Copyright © 2016年 黄威. All rights reserved.
//

#import "RegisterViewController.h"
#import "BaseTextField.h"
#import "BaseLabel.h"
#import "BaseButton.h"
#import "NSString+HVV.h"
#import "MyPhoneKey.h"
#import "UIImageView+WebCache.h"
#import "AFNetworking.h"
#import "Masonry.h"

@interface RegisterViewController ()
@property (nonatomic, retain) BaseTextField *email;
@property (nonatomic, retain) BaseTextField *userName;
@property (nonatomic, retain) BaseTextField *password;
@property (nonatomic, retain) BaseTextField *securityCode;
@property (nonatomic, retain) BaseLabel *labelOfEmail;
@property (nonatomic, retain) BaseLabel *labelOfUserName;
@property (nonatomic, retain) BaseLabel *labelOfPassword;
@property (nonatomic, retain) BaseLabel *labelOfSecurityCode;
@property (nonatomic, retain) UIImageView *imageViewOfSecurityCode;
@property (nonatomic, retain) BaseButton *buttonOfRefresh;
@property (nonatomic, retain) BaseButton *buttonOfRegister;
@property (nonatomic, assign) NSNumber *statusCode;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createView];
    [self reFresh];
}




- (void)createView{


    self.labelOfEmail = [[BaseLabel alloc]init];
    self.labelOfEmail.text = @"邮箱地址:";
    [self.labelOfEmail.layer setMasksToBounds:YES];
    [self.labelOfEmail.layer setCornerRadius:5];
    [self.view addSubview:self.labelOfEmail];
    [self.labelOfEmail mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(74);
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.24);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(0.08);
    }];
    
    self.email = [[BaseTextField alloc]init];
    self.email.borderStyle = UITextBorderStyleRoundedRect;
    self.email.clearsOnInsertion = YES;
    self.email.clearButtonMode = UITextFieldViewModeAlways;
    [self.view addSubview:self.email];
    [self.email mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.labelOfEmail.mas_right).mas_offset(10);
        make.top.mas_equalTo(74);
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.6);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(0.08);
    }];


    self.labelOfUserName = [[BaseLabel alloc]init];
    self.labelOfUserName.text = @"用户名:";
    [self.labelOfUserName.layer setMasksToBounds:YES];
    [self.labelOfUserName.layer setCornerRadius:5];
    [self.view addSubview:self.labelOfUserName];
    [self.labelOfUserName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(self.labelOfEmail.mas_bottom).mas_offset(20);
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.24);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(0.08);
    }];
    
    
    
    self.userName = [[BaseTextField alloc]init];
    self.userName.borderStyle = UITextBorderStyleRoundedRect;
    self.userName.clearsOnInsertion = YES;
    self.userName.clearButtonMode = UITextFieldViewModeAlways;
    [self.view addSubview:self.userName];
    [self.userName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.email);
        make.centerY.mas_equalTo(self.labelOfUserName);
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.6);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(0.08);
    }];


    self.labelOfPassword = [[BaseLabel alloc]init];
    self.labelOfPassword.text = @"密码:";
    [self.labelOfPassword.layer setMasksToBounds:YES];
    [self.labelOfPassword.layer setCornerRadius:5];
    [self.view addSubview:self.labelOfPassword];
    [self.labelOfPassword mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(self.labelOfUserName.mas_width);
        make.height.mas_equalTo(self.labelOfUserName.mas_height);
        make.trailing.mas_equalTo(self.labelOfUserName);
        make.top.mas_equalTo(self.labelOfUserName.mas_bottom).mas_offset(20);
    }];
    
    
    

    self.password = [[BaseTextField alloc]init];
    self.password.borderStyle = UITextBorderStyleRoundedRect;
    self.password.placeholder = @"请输入6位以上密码";
    self.password.clearsOnInsertion = YES;
    self.password.clearButtonMode = UITextFieldViewModeAlways;
    [self.view addSubview:self.password];
    [self.password mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.userName);
        make.centerY.mas_equalTo(self.labelOfPassword);
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.6);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(0.08);
    }];

    self.labelOfSecurityCode = [[BaseLabel alloc]init];
    self.labelOfSecurityCode.text = @"验证码:";
    [self.labelOfSecurityCode.layer setMasksToBounds:YES];
    [self.labelOfSecurityCode.layer setCornerRadius:5];
    [self.view addSubview:self.labelOfSecurityCode];
    [self.labelOfSecurityCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(self.labelOfUserName.mas_width);
        make.height.mas_equalTo(self.labelOfUserName.mas_height);
        make.trailing.mas_equalTo(self.labelOfUserName);
        make.top.mas_equalTo(self.labelOfPassword.mas_bottom).mas_offset(20);
    }];
    
    

    self.securityCode = [[BaseTextField alloc]init];
    self.securityCode.borderStyle = UITextBorderStyleRoundedRect;
    self.securityCode.clearsOnInsertion = YES;
    self.securityCode.clearButtonMode = UITextFieldViewModeAlways;
    [self.view addSubview:self.securityCode];
    [self.securityCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.6);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(0.08);
        make.centerX.mas_equalTo(self.password);
        make.centerY.mas_equalTo(self.labelOfSecurityCode);
    }];
    

    self.imageViewOfSecurityCode = [[UIImageView alloc]init];
  //  self.imageViewOfSecurityCode.backgroundColor = [UIColor purpleColor];
    [self.view addSubview:self.imageViewOfSecurityCode];
    [self.imageViewOfSecurityCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(self.labelOfUserName.mas_width);
        make.height.mas_equalTo(self.labelOfUserName.mas_height);
        make.centerX.mas_equalTo(self.labelOfSecurityCode);
        make.top.mas_equalTo(self.labelOfSecurityCode.mas_bottom).mas_equalTo(30);
        
    }];
    

    self.buttonOfRefresh = [BaseButton buttonWithType:UIButtonTypeCustom];
    [self.buttonOfRefresh setTitle:@"刷新验证码" forState: UIControlStateNormal];
    self.buttonOfRefresh.backgroundColor = [UIColor colorWithRed:18.0 / 255 green:86.0 / 255 blue:138.0 / 255 alpha:1];
    self.buttonOfRefresh.layer.masksToBounds = YES;
    self.buttonOfRefresh.layer.cornerRadius = 5;
    [self.view addSubview:self.buttonOfRefresh];
    [self.buttonOfRefresh mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.3);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(0.08);
        make.centerX.mas_equalTo(self.securityCode);
        make.centerY.mas_equalTo(self.imageViewOfSecurityCode);
        
    }];
    
    self.buttonOfRegister = [BaseButton buttonWithType:UIButtonTypeCustom];
    [self.buttonOfRegister setTitle:@"注册" forState: UIControlStateNormal];
    self.buttonOfRegister.backgroundColor = [UIColor colorWithRed:18.0 / 255 green:86.0 / 255 blue:138.0 / 255 alpha:1];
    self.buttonOfRegister.layer.masksToBounds = YES;
    self.buttonOfRegister.layer.cornerRadius = 5;
    [self.view addSubview:self.buttonOfRegister];
    [self.buttonOfRegister mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.6);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(0.08);
        make.top.mas_equalTo(self.imageViewOfSecurityCode.mas_bottom).mas_offset(40);
        make.centerX.mas_equalTo(self.view);
        
    }];
    
    
    
    [self.buttonOfRegister addTarget:self action:@selector(registerButton:) forControlEvents:UIControlEventTouchUpInside];
    NSURL *url = [NSURL URLWithString:self.strOfSecurityCode];
    self.imageViewOfSecurityCode.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
    [self.buttonOfRefresh addTarget:self action:@selector(reFresh) forControlEvents:UIControlEventTouchUpInside];
    
}


- (void)registerButton:(BaseButton *)button{

    
    
    
        if (![self.email.text isEmail:self.email.text]) {
    
            NSLog(@"输入邮箱不符合条件");
    
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"邮箱输入错了哦" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"好的,我重新输入" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                //按钮触发的方法
            }]];
    
            [self presentViewController:alert animated:YES completion:nil];
    
    
    
        }else if (![self.password.text isPassWord:self.password.text]) {
    
            NSLog(@"输入密码少于6位不符合条件 或者大于16位");
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"密码少于六位,不符合要求哦" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"好的,我重新输入" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                //按钮触发的方法
            }]];
    
            [self presentViewController:alert animated:YES completion:nil];
        
    
        }
    
        else if(self.securityCode.text.length == 0){
        
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"还没输入验证码" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"好的,我重新输入" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                //按钮触发的方法
            }]];
            
            [self presentViewController:alert animated:YES completion:nil];
            
        }
    
        else
        
        {
        
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            NSString *postURLstring = @"http://app.yanyue.cn/user/register";
            NSDictionary *parmeters = @{@"email":self.email.text,@"password":self.password.text,@"securityCode":self.securityCode.text,@"username":self.userName.text,@"openudid":@"OPENUUID"};
         
            [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            NSMutableSet *set = [NSMutableSet setWithSet:manager.responseSerializer.acceptableContentTypes];
            [set addObject:@"text/html"];
            [manager.responseSerializer setAcceptableContentTypes:set];
            
            // 设置请求POST发送
            [manager POST:postURLstring parameters:parmeters progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                self.statusCode = responseObject[@"status"];
                
                if ([self.statusCode integerValue] == -1) {
                  
                    
                    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"用户名不合法" message:@"重新输入" preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"是的" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                  
                    }]];
                
                    [self presentViewController:alert animated:YES completion:nil];
                    
                }else if([self.statusCode integerValue] == -3){
                
                    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"用户名已经存在" message:@"重新输入" preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"是的" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        //按钮触发的方法
                        [self.navigationController popViewControllerAnimated:YES];
                        
                    }]];
                    
                    [self presentViewController:alert animated:YES completion:nil];

                
                }else if ([self.statusCode integerValue] == 0){
                
                    NSLog(@"%@",self.statusCode);
                    
                    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"验证码错误" message:@"重新输入" preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"是的" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        //按钮触发的方法
                        [self.navigationController popViewControllerAnimated:YES];
                        
                    }]];
                    
                    [self presentViewController:alert animated:YES completion:nil];
                    
                }
                else if([self.statusCode integerValue] == 1){
                
                    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"注册成功" message:@"请牢记密码" preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"好的,我记住了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        //按钮触发的方法
                        [self.navigationController popViewControllerAnimated:YES];
                        
                    }]];
                    
                    [self presentViewController:alert animated:YES completion:nil];
                
                
                
                }
                
      /*
                 -1 用户名不合法
                 0 验证码错误
                 -3 用户名已经存在
                 */
         
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"请求失败: %@", error);
            }];
    
        
        }

}


#pragma mark - 刷新验证码的方法

- (void)reFresh{


    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postURLstring = @"http://app.yanyue.cn/public/securitycode";
    NSDictionary *parmeters = @{@"openudid":@"OPENUUID"};
    
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    
    NSMutableSet *set = [NSMutableSet setWithSet:manager.responseSerializer.acceptableContentTypes];
    [set addObject:@"text/html"];
    [manager.responseSerializer setAcceptableContentTypes:set];
    
    // 设置请求POST发送
    [manager POST:postURLstring parameters:parmeters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        NSString *strOfSecurityCode = responseObject[@"securityCode"];
        
        NSURL *url = [NSURL URLWithString:strOfSecurityCode];
        
        self.imageViewOfSecurityCode.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败: %@", error);
    }];
    



}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
